package cn.evun.sweet.demo.extend;

import java.io.PrintWriter;
import java.sql.DriverManager;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.io.IoBuilder;
import org.hsqldb.server.Server;

import cn.evun.sweet.core.common.R;

/**
 * 将HSQLDB的日志交由log4j2统一管理。
 *
 * @author yangw
 * @since V1.0.0
 */
public class HSQLDBCustomLogServer extends Server {
	
	public HSQLDBCustomLogServer() {
		super();
		IoBuilder logger = IoBuilder.forLogger(Server.class).setMarker(R.log.log_marker_dblog);
		/*设置输出流的日志级别，由于Console的最低级别是Debug，这里为了屏蔽HSQL的非ERR日志信息，所以设置为TRACE*/
		PrintWriter logPrint = logger.setLevel(Level.TRACE).buildPrintWriter();
		super.setLogWriter(logPrint);
		super.setErrWriter(logger.setLevel(Level.ERROR).buildPrintWriter());
		if(super.isTrace()){
			DriverManager.setLogWriter(logPrint);
		}
	}
	
	@Override
	protected void print(String msg) {
		PrintWriter writer = super.getLogWriter();
		if (writer != null) {
            writer.println(msg);
            writer.flush();
        }
    }
	
	@Override
	protected void printError(String msg) {
        PrintWriter writer = super.getErrWriter();
        if (writer != null) {
            writer.print("[" + Thread.currentThread() + "]: ");
            writer.println(msg);
            writer.flush();
        }
    }
}
